home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1998 November / Freeware November 1998.img / dist / fw_elisp-manual-19.idb / usr / freeware / info / elisp-7.z / elisp-7 (.txt)
GNU Info File  |  1998-05-26  |  46KB  |  899 lines

  1. This is Info file elisp, produced by Makeinfo-1.63 from the input file
  2. elisp.texi.
  3.    This version is the edition 2.4.2 of the GNU Emacs Lisp Reference
  4. Manual.  It corresponds to Emacs Version 19.34.
  5.    Published by the Free Software Foundation 59 Temple Place, Suite 330
  6. Boston, MA  02111-1307  USA
  7.    Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1996 Free Software
  8. Foundation, Inc.
  9.    Permission is granted to make and distribute verbatim copies of this
  10. manual provided the copyright notice and this permission notice are
  11. preserved on all copies.
  12.    Permission is granted to copy and distribute modified versions of
  13. this manual under the conditions for verbatim copying, provided that the
  14. entire resulting derived work is distributed under the terms of a
  15. permission notice identical to this one.
  16.    Permission is granted to copy and distribute translations of this
  17. manual into another language, under the above conditions for modified
  18. versions, except that this permission notice may be stated in a
  19. translation approved by the Foundation.
  20.    Permission is granted to copy and distribute modified versions of
  21. this manual under the conditions for verbatim copying, provided also
  22. that the section entitled "GNU General Public License" is included
  23. exactly as in the original, and provided that the entire resulting
  24. derived work is distributed under the terms of a permission notice
  25. identical to this one.
  26.    Permission is granted to copy and distribute translations of this
  27. manual into another language, under the above conditions for modified
  28. versions, except that the section entitled "GNU General Public License"
  29. may be included in a translation approved by the Free Software
  30. Foundation instead of in the original English.
  31. File: elisp,  Node: Eval,  Next: Forms,  Prev: Intro Eval,  Up: Evaluation
  32.    Most often, forms are evaluated automatically, by virtue of their
  33. occurrence in a program being run.  On rare occasions, you may need to
  34. write code that evaluates a form that is computed at run time, such as
  35. after reading a form from text being edited or getting one from a
  36. property list.  On these occasions, use the `eval' function.
  37.    *Note:* it is generally cleaner and more flexible to call functions
  38. that are stored in data structures, rather than to evaluate expressions
  39. stored in data structures.  Using functions provides the ability to
  40. pass information to them as arguments.
  41.    The functions and variables described in this section evaluate forms,
  42. specify limits to the evaluation process, or record recently returned
  43. values.  Loading a file also does evaluation (*note Loading::.).
  44.  - Function: eval FORM
  45.      This is the basic function for performing evaluation.  It evaluates
  46.      FORM in the current environment and returns the result.  How the
  47.      evaluation proceeds depends on the type of the object (*note
  48.      Forms::.).
  49.      Since `eval' is a function, the argument expression that appears
  50.      in a call to `eval' is evaluated twice: once as preparation before
  51.      `eval' is called, and again by the `eval' function itself.  Here
  52.      is an example:
  53.           (setq foo 'bar)
  54.                => bar
  55.           (setq bar 'baz)
  56.                => baz
  57.           ;; `eval' receives argument `bar', which is the value of `foo'
  58.           (eval foo)
  59.                => baz
  60.           (eval 'foo)
  61.                => bar
  62.      The number of currently active calls to `eval' is limited to
  63.      `max-lisp-eval-depth' (see below).
  64.  - Command: eval-region START END &optional STREAM
  65.      This function evaluates the forms in the current buffer in the
  66.      region defined by the positions START and END.  It reads forms from
  67.      the region and calls `eval' on them until the end of the region is
  68.      reached, or until an error is signaled and not handled.
  69.      If STREAM is supplied, `standard-output' is bound to it during the
  70.      evaluation.
  71.      You can use the variable `load-read-function' to specify a function
  72.      for `eval-region' to use instead of `read' for reading
  73.      expressions.  *Note How Programs Do Loading::.
  74.      `eval-region' always returns `nil'.
  75.  - Command: eval-current-buffer &optional STREAM
  76.      This is like `eval-region' except that it operates on the whole
  77.      buffer.
  78.  - Variable: max-lisp-eval-depth
  79.      This variable defines the maximum depth allowed in calls to `eval',
  80.      `apply', and `funcall' before an error is signaled (with error
  81.      message `"Lisp nesting exceeds max-lisp-eval-depth"').  This counts
  82.      internal uses of those functions, such as for calling the functions
  83.      mentioned in Lisp expressions, and recursive evaluation of
  84.      function call arguments and function body forms.
  85.      This limit, with the associated error when it is exceeded, is one
  86.      way that Lisp avoids infinite recursion on an ill-defined function.
  87.      The default value of this variable is 200.  If you set it to a
  88.      value less than 100, Lisp will reset it to 100 if the given value
  89.      is reached.
  90.      `max-specpdl-size' provides another limit on nesting.  *Note Local
  91.      Variables::.
  92.  - Variable: values
  93.      The value of this variable is a list of the values returned by all
  94.      the expressions that were read from buffers (including the
  95.      minibuffer), evaluated, and printed.  The elements are ordered
  96.      most recent first.
  97.           (setq x 1)
  98.                => 1
  99.           (list 'A (1+ 2) auto-save-default)
  100.                => (A 3 t)
  101.           values
  102.                => ((A 3 t) 1 ...)
  103.      This variable is useful for referring back to values of forms
  104.      recently evaluated.  It is generally a bad idea to print the value
  105.      of `values' itself, since this may be very long.  Instead, examine
  106.      particular elements, like this:
  107.           ;; Refer to the most recent evaluation result.
  108.           (nth 0 values)
  109.                => (A 3 t)
  110.           ;; That put a new element on,
  111.           ;;   so all elements move back one.
  112.           (nth 1 values)
  113.                => (A 3 t)
  114.           ;; This gets the element that was next-to-most-recent
  115.           ;;   before this example.
  116.           (nth 3 values)
  117.                => 1
  118. File: elisp,  Node: Forms,  Next: Quoting,  Prev: Eval,  Up: Evaluation
  119. Kinds of Forms
  120. ==============
  121.    A Lisp object that is intended to be evaluated is called a "form".
  122. How Emacs evaluates a form depends on its data type.  Emacs has three
  123. different kinds of form that are evaluated differently: symbols, lists,
  124. and "all other types".  This section describes all three kinds,
  125. starting with "all other types" which are self-evaluating forms.
  126. * Menu:
  127. * Self-Evaluating Forms::   Forms that evaluate to themselves.
  128. * Symbol Forms::            Symbols evaluate as variables.
  129. * Classifying Lists::       How to distinguish various sorts of list forms.
  130. * Function Indirection::    When a symbol appears as the car of a list,
  131.                   we find the real function via the symbol.
  132. * Function Forms::          Forms that call functions.
  133. * Macro Forms::             Forms that call macros.
  134. * Special Forms::           "Special forms" are idiosyncratic primitives,
  135.                               most of them extremely important.
  136. * Autoloading::             Functions set up to load files
  137.                               containing their real definitions.
  138. File: elisp,  Node: Self-Evaluating Forms,  Next: Symbol Forms,  Up: Forms
  139. Self-Evaluating Forms
  140. ---------------------
  141.    A "self-evaluating form" is any form that is not a list or symbol.
  142. Self-evaluating forms evaluate to themselves: the result of evaluation
  143. is the same object that was evaluated.  Thus, the number 25 evaluates to
  144. 25, and the string `"foo"' evaluates to the string `"foo"'.  Likewise,
  145. evaluation of a vector does not cause evaluation of the elements of the
  146. vector--it returns the same vector with its contents unchanged.
  147.      '123               ; An object, shown without evaluation.
  148.           => 123
  149.      123                ; Evaluated as usual---result is the same.
  150.           => 123
  151.      (eval '123)        ; Evaluated ``by hand''---result is the same.
  152.           => 123
  153.      (eval (eval '123)) ; Evaluating twice changes nothing.
  154.           => 123
  155.    It is common to write numbers, characters, strings, and even vectors
  156. in Lisp code, taking advantage of the fact that they self-evaluate.
  157. However, it is quite unusual to do this for types that lack a read
  158. syntax, because there's no way to write them textually.  It is possible
  159. to construct Lisp expressions containing these types by means of a Lisp
  160. program.  Here is an example:
  161.      ;; Build an expression containing a buffer object.
  162.      (setq buffer (list 'print (current-buffer)))
  163.           => (print #<buffer eval.texi>)
  164.      ;; Evaluate it.
  165.      (eval buffer)
  166.           -| #<buffer eval.texi>
  167.           => #<buffer eval.texi>
  168. File: elisp,  Node: Symbol Forms,  Next: Classifying Lists,  Prev: Self-Evaluating Forms,  Up: Forms
  169. Symbol Forms
  170. ------------
  171.    When a symbol is evaluated, it is treated as a variable.  The result
  172. is the variable's value, if it has one.  If it has none (if its value
  173. cell is void), an error is signaled.  For more information on the use of
  174. variables, see *Note Variables::.
  175.    In the following example, we set the value of a symbol with `setq'.
  176. Then we evaluate the symbol, and get back the value that `setq' stored.
  177.      (setq a 123)
  178.           => 123
  179.      (eval 'a)
  180.           => 123
  181.      a
  182.           => 123
  183.    The symbols `nil' and `t' are treated specially, so that the value
  184. of `nil' is always `nil', and the value of `t' is always `t'; you
  185. cannot set or bind them to any other values.  Thus, these two symbols
  186. act like self-evaluating forms, even though `eval' treats them like any
  187. other symbol.
  188. File: elisp,  Node: Classifying Lists,  Next: Function Indirection,  Prev: Symbol Forms,  Up: Forms
  189. Classification of List Forms
  190. ----------------------------
  191.    A form that is a nonempty list is either a function call, a macro
  192. call, or a special form, according to its first element.  These three
  193. kinds of forms are evaluated in different ways, described below.  The
  194. remaining list elements constitute the "arguments" for the function,
  195. macro, or special form.
  196.    The first step in evaluating a nonempty list is to examine its first
  197. element.  This element alone determines what kind of form the list is
  198. and how the rest of the list is to be processed.  The first element is
  199. *not* evaluated, as it would be in some Lisp dialects such as Scheme.
  200. File: elisp,  Node: Function Indirection,  Next: Function Forms,  Prev: Classifying Lists,  Up: Forms
  201. Symbol Function Indirection
  202. ---------------------------
  203.    If the first element of the list is a symbol then evaluation examines
  204. the symbol's function cell, and uses its contents instead of the
  205. original symbol.  If the contents are another symbol, this process,
  206. called "symbol function indirection", is repeated until it obtains a
  207. non-symbol.  *Note Function Names::, for more information about using a
  208. symbol as a name for a function stored in the function cell of the
  209. symbol.
  210.    One possible consequence of this process is an infinite loop, in the
  211. event that a symbol's function cell refers to the same symbol.  Or a
  212. symbol may have a void function cell, in which case the subroutine
  213. `symbol-function' signals a `void-function' error.  But if neither of
  214. these things happens, we eventually obtain a non-symbol, which ought to
  215. be a function or other suitable object.
  216.    More precisely, we should now have a Lisp function (a lambda
  217. expression), a byte-code function, a primitive function, a Lisp macro, a
  218. special form, or an autoload object.  Each of these types is a case
  219. described in one of the following sections.  If the object is not one of
  220. these types, the error `invalid-function' is signaled.
  221.    The following example illustrates the symbol indirection process.  We
  222. use `fset' to set the function cell of a symbol and `symbol-function'
  223. to get the function cell contents (*note Function Cells::.).
  224. Specifically, we store the symbol `car' into the function cell of
  225. `first', and the symbol `first' into the function cell of `erste'.
  226.      ;; Build this function cell linkage:
  227.      ;;   -------------       -----        -------        -------
  228.      ;;  | #<subr car> | <-- | car |  <-- | first |  <-- | erste |
  229.      ;;   -------------       -----        -------        -------
  230.      (symbol-function 'car)
  231.           => #<subr car>
  232.      (fset 'first 'car)
  233.           => car
  234.      (fset 'erste 'first)
  235.           => first
  236.      (erste '(1 2 3))   ; Call the function referenced by `erste'.
  237.           => 1
  238.    By contrast, the following example calls a function without any
  239. symbol function indirection, because the first element is an anonymous
  240. Lisp function, not a symbol.
  241.      ((lambda (arg) (erste arg))
  242.       '(1 2 3))
  243.           => 1
  244. Executing the function itself evaluates its body; this does involve
  245. symbol function indirection when calling `erste'.
  246.    The built-in function `indirect-function' provides an easy way to
  247. perform symbol function indirection explicitly.
  248.  - Function: indirect-function FUNCTION
  249.      This function returns the meaning of FUNCTION as a function.  If
  250.      FUNCTION is a symbol, then it finds FUNCTION's function definition
  251.      and starts over with that value.  If FUNCTION is not a symbol,
  252.      then it returns FUNCTION itself.
  253.      Here is how you could define `indirect-function' in Lisp:
  254.           (defun indirect-function (function)
  255.             (if (symbolp function)
  256.                 (indirect-function (symbol-function function))
  257.               function))
  258. File: elisp,  Node: Function Forms,  Next: Macro Forms,  Prev: Function Indirection,  Up: Forms
  259. Evaluation of Function Forms
  260. ----------------------------
  261.    If the first element of a list being evaluated is a Lisp function
  262. object, byte-code object or primitive function object, then that list is
  263. a "function call".  For example, here is a call to the function `+':
  264.      (+ 1 x)
  265.    The first step in evaluating a function call is to evaluate the
  266. remaining elements of the list from left to right.  The results are the
  267. actual argument values, one value for each list element.  The next step
  268. is to call the function with this list of arguments, effectively using
  269. the function `apply' (*note Calling Functions::.).  If the function is
  270. written in Lisp, the arguments are used to bind the argument variables
  271. of the function (*note Lambda Expressions::.); then the forms in the
  272. function body are evaluated in order, and the value of the last body
  273. form becomes the value of the function call.
  274. File: elisp,  Node: Macro Forms,  Next: Special Forms,  Prev: Function Forms,  Up: Forms
  275. Lisp Macro Evaluation
  276. ---------------------
  277.    If the first element of a list being evaluated is a macro object,
  278. then the list is a "macro call".  When a macro call is evaluated, the
  279. elements of the rest of the list are *not* initially evaluated.
  280. Instead, these elements themselves are used as the arguments of the
  281. macro.  The macro definition computes a replacement form, called the
  282. "expansion" of the macro, to be evaluated in place of the original
  283. form.  The expansion may be any sort of form: a self-evaluating
  284. constant, a symbol, or a list.  If the expansion is itself a macro call,
  285. this process of expansion repeats until some other sort of form results.
  286.    Ordinary evaluation of a macro call finishes by evaluating the
  287. expansion.  However, the macro expansion is not necessarily evaluated
  288. right away, or at all, because other programs also expand macro calls,
  289. and they may or may not evaluate the expansions.
  290.    Normally, the argument expressions are not evaluated as part of
  291. computing the macro expansion, but instead appear as part of the
  292. expansion, so they are computed when the expansion is computed.
  293.    For example, given a macro defined as follows:
  294.      (defmacro cadr (x)
  295.        (list 'car (list 'cdr x)))
  296. an expression such as `(cadr (assq 'handler list))' is a macro call,
  297. and its expansion is:
  298.      (car (cdr (assq 'handler list)))
  299. Note that the argument `(assq 'handler list)' appears in the expansion.
  300.    *Note Macros::, for a complete description of Emacs Lisp macros.
  301. File: elisp,  Node: Special Forms,  Next: Autoloading,  Prev: Macro Forms,  Up: Forms
  302. Special Forms
  303. -------------
  304.    A "special form" is a primitive function specially marked so that
  305. its arguments are not all evaluated.  Most special forms define control
  306. structures or perform variable bindings--things which functions cannot
  307.    Each special form has its own rules for which arguments are evaluated
  308. and which are used without evaluation.  Whether a particular argument is
  309. evaluated may depend on the results of evaluating other arguments.
  310.    Here is a list, in alphabetical order, of all of the special forms in
  311. Emacs Lisp with a reference to where each is described.
  312. `and'
  313.      *note Combining Conditions::.
  314. `catch'
  315.      *note Catch and Throw::.
  316. `cond'
  317.      *note Conditionals::.
  318. `condition-case'
  319.      *note Handling Errors::.
  320. `defconst'
  321.      *note Defining Variables::.
  322. `defmacro'
  323.      *note Defining Macros::.
  324. `defun'
  325.      *note Defining Functions::.
  326. `defvar'
  327.      *note Defining Variables::.
  328. `function'
  329.      *note Anonymous Functions::.
  330.      *note Conditionals::.
  331. `interactive'
  332.      *note Interactive Call::.
  333. `let'
  334. `let*'
  335.      *note Local Variables::.
  336.      *note Combining Conditions::.
  337. `prog1'
  338. `prog2'
  339. `progn'
  340.      *note Sequencing::.
  341. `quote'
  342.      *note Quoting::.
  343. `save-excursion'
  344.      *note Excursions::.
  345. `save-restriction'
  346.      *note Narrowing::.
  347. `save-window-excursion'
  348.      *note Window Configurations::.
  349. `setq'
  350.      *note Setting Variables::.
  351. `setq-default'
  352.      *note Creating Buffer-Local::.
  353. `track-mouse'
  354.      *note Mouse Tracking::.
  355. `unwind-protect'
  356.      *note Nonlocal Exits::.
  357. `while'
  358.      *note Iteration::.
  359. `with-output-to-temp-buffer'
  360.      *note Temporary Displays::.
  361.      Common Lisp note: Here are some comparisons of special forms in
  362.      GNU Emacs Lisp and Common Lisp.  `setq', `if', and `catch' are
  363.      special forms in both Emacs Lisp and Common Lisp.  `defun' is a
  364.      special form in Emacs Lisp, but a macro in Common Lisp.
  365.      `save-excursion' is a special form in Emacs Lisp, but doesn't
  366.      exist in Common Lisp.  `throw' is a special form in Common Lisp
  367.      (because it must be able to throw multiple values), but it is a
  368.      function in Emacs Lisp (which doesn't have multiple values).
  369. File: elisp,  Node: Autoloading,  Prev: Special Forms,  Up: Forms
  370. Autoloading
  371. -----------
  372.    The "autoload" feature allows you to call a function or macro whose
  373. function definition has not yet been loaded into Emacs.  It specifies
  374. which file contains the definition.  When an autoload object appears as
  375. a symbol's function definition, calling that symbol as a function
  376. automatically loads the specified file; then it calls the real
  377. definition loaded from that file.  *Note Autoload::.
  378. File: elisp,  Node: Quoting,  Prev: Forms,  Up: Evaluation
  379. Quoting
  380. =======
  381.    The special form `quote' returns its single argument, as written,
  382. without evaluating it.  This provides a way to include constant symbols
  383. and lists, which are not self-evaluating objects, in a program.  (It is
  384. not necessary to quote self-evaluating objects such as numbers, strings,
  385. and vectors.)
  386.  - Special Form: quote OBJECT
  387.      This special form returns OBJECT, without evaluating it.
  388.    Because `quote' is used so often in programs, Lisp provides a
  389. convenient read syntax for it.  An apostrophe character (`'') followed
  390. by a Lisp object (in read syntax) expands to a list whose first element
  391. is `quote', and whose second element is the object.  Thus, the read
  392. syntax `'x' is an abbreviation for `(quote x)'.
  393.    Here are some examples of expressions that use `quote':
  394.      (quote (+ 1 2))
  395.           => (+ 1 2)
  396.      (quote foo)
  397.           => foo
  398.      'foo
  399.           => foo
  400.      ''foo
  401.           => (quote foo)
  402.      '(quote foo)
  403.           => (quote foo)
  404.      ['foo]
  405.           => [(quote foo)]
  406.    Other quoting constructs include `function' (*note Anonymous
  407. Functions::.), which causes an anonymous lambda expression written in
  408. Lisp to be compiled, and ``' (*note Backquote::.), which is used to
  409. quote only part of a list, while computing and substituting other parts.
  410. File: elisp,  Node: Control Structures,  Next: Variables,  Prev: Evaluation,  Up: Top
  411. Control Structures
  412. ******************
  413.    A Lisp program consists of expressions or "forms" (*note Forms::.).
  414. We control the order of execution of the forms by enclosing them in
  415. "control structures".  Control structures are special forms which
  416. control when, whether, or how many times to execute the forms they
  417. contain.
  418.    The simplest order of execution is sequential execution: first form
  419. A, then form B, and so on.  This is what happens when you write several
  420. forms in succession in the body of a function, or at top level in a
  421. file of Lisp code--the forms are executed in the order written.  We
  422. call this "textual order".  For example, if a function body consists of
  423. two forms A and B, evaluation of the function evaluates first A and
  424. then B, and the function's value is the value of B.
  425.    Explicit control structures make possible an order of execution other
  426. than sequential.
  427.    Emacs Lisp provides several kinds of control structure, including
  428. other varieties of sequencing, conditionals, iteration, and (controlled)
  429. jumps--all discussed below.  The built-in control structures are
  430. special forms since their subforms are not necessarily evaluated or not
  431. evaluated sequentially.  You can use macros to define your own control
  432. structure constructs (*note Macros::.).
  433. * Menu:
  434. * Sequencing::             Evaluation in textual order.
  435. * Conditionals::           `if', `cond'.
  436. * Combining Conditions::   `and', `or', `not'.
  437. * Iteration::              `while' loops.
  438. * Nonlocal Exits::         Jumping out of a sequence.
  439. File: elisp,  Node: Sequencing,  Next: Conditionals,  Up: Control Structures
  440. Sequencing
  441. ==========
  442.    Evaluating forms in the order they appear is the most common way
  443. control passes from one form to another.  In some contexts, such as in a
  444. function body, this happens automatically.  Elsewhere you must use a
  445. control structure construct to do this: `progn', the simplest control
  446. construct of Lisp.
  447.    A `progn' special form looks like this:
  448.      (progn A B C ...)
  449. and it says to execute the forms A, B, C and so on, in that order.
  450. These forms are called the body of the `progn' form.  The value of the
  451. last form in the body becomes the value of the entire `progn'.
  452.    In the early days of Lisp, `progn' was the only way to execute two
  453. or more forms in succession and use the value of the last of them.  But
  454. programmers found they often needed to use a `progn' in the body of a
  455. function, where (at that time) only one form was allowed.  So the body
  456. of a function was made into an "implicit `progn'": several forms are
  457. allowed just as in the body of an actual `progn'.  Many other control
  458. structures likewise contain an implicit `progn'.  As a result, `progn'
  459. is not used as often as it used to be.  It is needed now most often
  460. inside an `unwind-protect', `and', `or', or in the THEN-part of an `if'.
  461.  - Special Form: progn FORMS...
  462.      This special form evaluates all of the FORMS, in textual order,
  463.      returning the result of the final form.
  464.           (progn (print "The first form")
  465.                  (print "The second form")
  466.                  (print "The third form"))
  467.                -| "The first form"
  468.                -| "The second form"
  469.                -| "The third form"
  470.           => "The third form"
  471.    Two other control constructs likewise evaluate a series of forms but
  472. return a different value:
  473.  - Special Form: prog1 FORM1 FORMS...
  474.      This special form evaluates FORM1 and all of the FORMS, in textual
  475.      order, returning the result of FORM1.
  476.           (prog1 (print "The first form")
  477.                  (print "The second form")
  478.                  (print "The third form"))
  479.                -| "The first form"
  480.                -| "The second form"
  481.                -| "The third form"
  482.           => "The first form"
  483.      Here is a way to remove the first element from a list in the
  484.      variable `x', then return the value of that former element:
  485.           (prog1 (car x) (setq x (cdr x)))
  486.  - Special Form: prog2 FORM1 FORM2 FORMS...
  487.      This special form evaluates FORM1, FORM2, and all of the following
  488.      FORMS, in textual order, returning the result of FORM2.
  489.           (prog2 (print "The first form")
  490.                  (print "The second form")
  491.                  (print "The third form"))
  492.                -| "The first form"
  493.                -| "The second form"
  494.                -| "The third form"
  495.           => "The second form"
  496. File: elisp,  Node: Conditionals,  Next: Combining Conditions,  Prev: Sequencing,  Up: Control Structures
  497. Conditionals
  498. ============
  499.    Conditional control structures choose among alternatives.  Emacs Lisp
  500. has two conditional forms: `if', which is much the same as in other
  501. languages, and `cond', which is a generalized case statement.
  502.  - Special Form: if CONDITION THEN-FORM ELSE-FORMS...
  503.      `if' chooses between the THEN-FORM and the ELSE-FORMS based on the
  504.      value of CONDITION.  If the evaluated CONDITION is non-`nil',
  505.      THEN-FORM is evaluated and the result returned.  Otherwise, the
  506.      ELSE-FORMS are evaluated in textual order, and the value of the
  507.      last one is returned.  (The ELSE part of `if' is an example of an
  508.      implicit `progn'.  *Note Sequencing::.)
  509.      If CONDITION has the value `nil', and no ELSE-FORMS are given,
  510.      `if' returns `nil'.
  511.      `if' is a special form because the branch that is not selected is
  512.      never evaluated--it is ignored.  Thus, in the example below,
  513.      `true' is not printed because `print' is never called.
  514.           (if nil
  515.               (print 'true)
  516.             'very-false)
  517.           => very-false
  518.  - Special Form: cond CLAUSE...
  519.      `cond' chooses among an arbitrary number of alternatives.  Each
  520.      CLAUSE in the `cond' must be a list.  The CAR of this list is the
  521.      CONDITION; the remaining elements, if any, the BODY-FORMS.  Thus,
  522.      a clause looks like this:
  523.           (CONDITION BODY-FORMS...)
  524.      `cond' tries the clauses in textual order, by evaluating the
  525.      CONDITION of each clause.  If the value of CONDITION is non-`nil',
  526.      the clause "succeeds"; then `cond' evaluates its BODY-FORMS, and
  527.      the value of the last of BODY-FORMS becomes the value of the
  528.      `cond'.  The remaining clauses are ignored.
  529.      If the value of CONDITION is `nil', the clause "fails", so the
  530.      `cond' moves on to the following clause, trying its CONDITION.
  531.      If every CONDITION evaluates to `nil', so that every clause fails,
  532.      `cond' returns `nil'.
  533.      A clause may also look like this:
  534.           (CONDITION)
  535.      Then, if CONDITION is non-`nil' when tested, the value of
  536.      CONDITION becomes the value of the `cond' form.
  537.      The following example has four clauses, which test for the cases
  538.      where the value of `x' is a number, string, buffer and symbol,
  539.      respectively:
  540.           (cond ((numberp x) x)
  541.                 ((stringp x) x)
  542.                 ((bufferp x)
  543.                  (setq temporary-hack x) ; multiple body-forms
  544.                  (buffer-name x))        ; in one clause
  545.                 ((symbolp x) (symbol-value x)))
  546.      Often we want to execute the last clause whenever none of the
  547.      previous clauses was successful.  To do this, we use `t' as the
  548.      CONDITION of the last clause, like this: `(t BODY-FORMS)'.  The
  549.      form `t' evaluates to `t', which is never `nil', so this clause
  550.      never fails, provided the `cond' gets to it at all.
  551.      For example,
  552.           (cond ((eq a 'hack) 'foo)
  553.                 (t "default"))
  554.           => "default"
  555.      This expression is a `cond' which returns `foo' if the value of
  556.      `a' is 1, and returns the string `"default"' otherwise.
  557.    Any conditional construct can be expressed with `cond' or with `if'.
  558. Therefore, the choice between them is a matter of style.  For example:
  559.      (if A B C)
  560.      ==
  561.      (cond (A B) (t C))
  562. File: elisp,  Node: Combining Conditions,  Next: Iteration,  Prev: Conditionals,  Up: Control Structures
  563. Constructs for Combining Conditions
  564. ===================================
  565.    This section describes three constructs that are often used together
  566. with `if' and `cond' to express complicated conditions.  The constructs
  567. `and' and `or' can also be used individually as kinds of multiple
  568. conditional constructs.
  569.  - Function: not CONDITION
  570.      This function tests for the falsehood of CONDITION.  It returns
  571.      `t' if CONDITION is `nil', and `nil' otherwise.  The function
  572.      `not' is identical to `null', and we recommend using the name
  573.      `null' if you are testing for an empty list.
  574.  - Special Form: and CONDITIONS...
  575.      The `and' special form tests whether all the CONDITIONS are true.
  576.      It works by evaluating the CONDITIONS one by one in the order
  577.      written.
  578.      If any of the CONDITIONS evaluates to `nil', then the result of
  579.      the `and' must be `nil' regardless of the remaining CONDITIONS; so
  580.      `and' returns right away, ignoring the remaining CONDITIONS.
  581.      If all the CONDITIONS turn out non-`nil', then the value of the
  582.      last of them becomes the value of the `and' form.
  583.      Here is an example.  The first condition returns the integer 1,
  584.      which is not `nil'.  Similarly, the second condition returns the
  585.      integer 2, which is not `nil'.  The third condition is `nil', so
  586.      the remaining condition is never evaluated.
  587.           (and (print 1) (print 2) nil (print 3))
  588.                -| 1
  589.                -| 2
  590.           => nil
  591.      Here is a more realistic example of using `and':
  592.           (if (and (consp foo) (eq (car foo) 'x))
  593.               (message "foo is a list starting with x"))
  594.      Note that `(car foo)' is not executed if `(consp foo)' returns
  595.      `nil', thus avoiding an error.
  596.      `and' can be expressed in terms of either `if' or `cond'.  For
  597.      example:
  598.           (and ARG1 ARG2 ARG3)
  599.           ==
  600.           (if ARG1 (if ARG2 ARG3))
  601.           ==
  602.           (cond (ARG1 (cond (ARG2 ARG3))))
  603.  - Special Form: or CONDITIONS...
  604.      The `or' special form tests whether at least one of the CONDITIONS
  605.      is true.  It works by evaluating all the CONDITIONS one by one in
  606.      the order written.
  607.      If any of the CONDITIONS evaluates to a non-`nil' value, then the
  608.      result of the `or' must be non-`nil'; so `or' returns right away,
  609.      ignoring the remaining CONDITIONS.  The value it returns is the
  610.      non-`nil' value of the condition just evaluated.
  611.      If all the CONDITIONS turn out `nil', then the `or' expression
  612.      returns `nil'.
  613.      For example, this expression tests whether `x' is either 0 or
  614.      `nil':
  615.           (or (eq x nil) (eq x 0))
  616.      Like the `and' construct, `or' can be written in terms of `cond'.
  617.      For example:
  618.           (or ARG1 ARG2 ARG3)
  619.           ==
  620.           (cond (ARG1)
  621.                 (ARG2)
  622.                 (ARG3))
  623.      You could almost write `or' in terms of `if', but not quite:
  624.           (if ARG1 ARG1
  625.             (if ARG2 ARG2
  626.               ARG3))
  627.      This is not completely equivalent because it can evaluate ARG1 or
  628.      ARG2 twice.  By contrast, `(or ARG1 ARG2 ARG3)' never evaluates
  629.      any argument more than once.
  630. File: elisp,  Node: Iteration,  Next: Nonlocal Exits,  Prev: Combining Conditions,  Up: Control Structures
  631. Iteration
  632. =========
  633.    Iteration means executing part of a program repetitively.  For
  634. example, you might want to repeat some computation once for each element
  635. of a list, or once for each integer from 0 to N.  You can do this in
  636. Emacs Lisp with the special form `while':
  637.  - Special Form: while CONDITION FORMS...
  638.      `while' first evaluates CONDITION.  If the result is non-`nil', it
  639.      evaluates FORMS in textual order.  Then it reevaluates CONDITION,
  640.      and if the result is non-`nil', it evaluates FORMS again.  This
  641.      process repeats until CONDITION evaluates to `nil'.
  642.      There is no limit on the number of iterations that may occur.  The
  643.      loop will continue until either CONDITION evaluates to `nil' or
  644.      until an error or `throw' jumps out of it (*note Nonlocal
  645.      Exits::.).
  646.      The value of a `while' form is always `nil'.
  647.           (setq num 0)
  648.                => 0
  649.           (while (< num 4)
  650.             (princ (format "Iteration %d." num))
  651.             (setq num (1+ num)))
  652.                -| Iteration 0.
  653.                -| Iteration 1.
  654.                -| Iteration 2.
  655.                -| Iteration 3.
  656.                => nil
  657.      If you would like to execute something on each iteration before the
  658.      end-test, put it together with the end-test in a `progn' as the
  659.      first argument of `while', as shown here:
  660.           (while (progn
  661.                    (forward-line 1)
  662.                    (not (looking-at "^$"))))
  663.      This moves forward one line and continues moving by lines until it
  664.      reaches an empty.  It is unusual in that the `while' has no body,
  665.      just the end test (which also does the real work of moving point).
  666. File: elisp,  Node: Nonlocal Exits,  Prev: Iteration,  Up: Control Structures
  667. Nonlocal Exits
  668. ==============
  669.    A "nonlocal exit" is a transfer of control from one point in a
  670. program to another remote point.  Nonlocal exits can occur in Emacs Lisp
  671. as a result of errors; you can also use them under explicit control.
  672. Nonlocal exits unbind all variable bindings made by the constructs being
  673. exited.
  674. * Menu:
  675. * Catch and Throw::     Nonlocal exits for the program's own purposes.
  676. * Examples of Catch::   Showing how such nonlocal exits can be written.
  677. * Errors::              How errors are signaled and handled.
  678. * Cleanups::            Arranging to run a cleanup form if an error happens.
  679. File: elisp,  Node: Catch and Throw,  Next: Examples of Catch,  Up: Nonlocal Exits
  680. Explicit Nonlocal Exits: `catch' and `throw'
  681. --------------------------------------------
  682.    Most control constructs affect only the flow of control within the
  683. construct itself.  The function `throw' is the exception to this rule
  684. of normal program execution: it performs a nonlocal exit on request.
  685. (There are other exceptions, but they are for error handling only.)
  686. `throw' is used inside a `catch', and jumps back to that `catch'.  For
  687. example:
  688.      (catch 'foo
  689.        (progn
  690.          ...
  691.          (throw 'foo t)
  692.          ...))
  693. The `throw' transfers control straight back to the corresponding
  694. `catch', which returns immediately.  The code following the `throw' is
  695. not executed.  The second argument of `throw' is used as the return
  696. value of the `catch'.
  697.    The `throw' and the `catch' are matched through the first argument:
  698. `throw' searches for a `catch' whose first argument is `eq' to the one
  699. specified.  Thus, in the above example, the `throw' specifies `foo',
  700. and the `catch' specifies the same symbol, so that `catch' is
  701. applicable.  If there is more than one applicable `catch', the
  702. innermost one takes precedence.
  703.    Executing `throw' exits all Lisp constructs up to the matching
  704. `catch', including function calls.  When binding constructs such as
  705. `let' or function calls are exited in this way, the bindings are
  706. unbound, just as they are when these constructs exit normally (*note
  707. Local Variables::.).  Likewise, `throw' restores the buffer and
  708. position saved by `save-excursion' (*note Excursions::.), and the
  709. narrowing status saved by `save-restriction' and the window selection
  710. saved by `save-window-excursion' (*note Window Configurations::.).  It
  711. also runs any cleanups established with the `unwind-protect' special
  712. form when it exits that form (*note Cleanups::.).
  713.    The `throw' need not appear lexically within the `catch' that it
  714. jumps to.  It can equally well be called from another function called
  715. within the `catch'.  As long as the `throw' takes place chronologically
  716. after entry to the `catch', and chronologically before exit from it, it
  717. has access to that `catch'.  This is why `throw' can be used in
  718. commands such as `exit-recursive-edit' that throw back to the editor
  719. command loop (*note Recursive Editing::.).
  720.      Common Lisp note: Most other versions of Lisp, including Common
  721.      Lisp, have several ways of transferring control nonsequentially:
  722.      `return', `return-from', and `go', for example.  Emacs Lisp has
  723.      only `throw'.
  724.  - Special Form: catch TAG BODY...
  725.      `catch' establishes a return point for the `throw' function.  The
  726.      return point is distinguished from other such return points by TAG,
  727.      which may be any Lisp object.  The argument TAG is evaluated
  728.      normally before the return point is established.
  729.      With the return point in effect, `catch' evaluates the forms of the
  730.      BODY in textual order.  If the forms execute normally, without
  731.      error or nonlocal exit, the value of the last body form is
  732.      returned from the `catch'.
  733.      If a `throw' is done within BODY specifying the same value TAG,
  734.      the `catch' exits immediately; the value it returns is whatever
  735.      was specified as the second argument of `throw'.
  736.  - Function: throw TAG VALUE
  737.      The purpose of `throw' is to return from a return point previously
  738.      established with `catch'.  The argument TAG is used to choose
  739.      among the various existing return points; it must be `eq' to the
  740.      value specified in the `catch'.  If multiple return points match
  741.      TAG, the innermost one is used.
  742.      The argument VALUE is used as the value to return from that
  743.      `catch'.
  744.      If no return point is in effect with tag TAG, then a `no-catch'
  745.      error is signaled with data `(TAG VALUE)'.
  746. File: elisp,  Node: Examples of Catch,  Next: Errors,  Prev: Catch and Throw,  Up: Nonlocal Exits
  747. Examples of `catch' and `throw'
  748. -------------------------------
  749.    One way to use `catch' and `throw' is to exit from a doubly nested
  750. loop.  (In most languages, this would be done with a "go to".) Here we
  751. compute `(foo I J)' for I and J varying from 0 to 9:
  752.      (defun search-foo ()
  753.        (catch 'loop
  754.          (let ((i 0))
  755.            (while (< i 10)
  756.              (let ((j 0))
  757.                (while (< j 10)
  758.                  (if (foo i j)
  759.                      (throw 'loop (list i j)))
  760.                  (setq j (1+ j))))
  761.              (setq i (1+ i))))))
  762. If `foo' ever returns non-`nil', we stop immediately and return a list
  763. of I and J.  If `foo' always returns `nil', the `catch' returns
  764. normally, and the value is `nil', since that is the result of the
  765. `while'.
  766.    Here are two tricky examples, slightly different, showing two return
  767. points at once.  First, two return points with the same tag, `hack':
  768.      (defun catch2 (tag)
  769.        (catch tag
  770.          (throw 'hack 'yes)))
  771.      => catch2
  772.      
  773.      (catch 'hack
  774.        (print (catch2 'hack))
  775.        'no)
  776.      -| yes
  777.      => no
  778. Since both return points have tags that match the `throw', it goes to
  779. the inner one, the one established in `catch2'.  Therefore, `catch2'
  780. returns normally with value `yes', and this value is printed.  Finally
  781. the second body form in the outer `catch', which is `'no', is evaluated
  782. and returned from the outer `catch'.
  783.    Now let's change the argument given to `catch2':
  784.      (defun catch2 (tag)
  785.        (catch tag
  786.          (throw 'hack 'yes)))
  787.      => catch2
  788.      
  789.      (catch 'hack
  790.        (print (catch2 'quux))
  791.        'no)
  792.      => yes
  793. We still have two return points, but this time only the outer one has
  794. the tag `hack'; the inner one has the tag `quux' instead.  Therefore,
  795. `throw' makes the outer `catch' return the value `yes'.  The function
  796. `print' is never called, and the body-form `'no' is never evaluated.
  797. File: elisp,  Node: Errors,  Next: Cleanups,  Prev: Examples of Catch,  Up: Nonlocal Exits
  798. Errors
  799. ------
  800.    When Emacs Lisp attempts to evaluate a form that, for some reason,
  801. cannot be evaluated, it "signals" an "error".
  802.    When an error is signaled, Emacs's default reaction is to print an
  803. error message and terminate execution of the current command.  This is
  804. the right thing to do in most cases, such as if you type `C-f' at the
  805. end of the buffer.
  806.    In complicated programs, simple termination may not be what you want.
  807. For example, the program may have made temporary changes in data
  808. structures, or created temporary buffers that should be deleted before
  809. the program is finished.  In such cases, you would use `unwind-protect'
  810. to establish "cleanup expressions" to be evaluated in case of error.
  811. (*Note Cleanups::.)  Occasionally, you may wish the program to continue
  812. execution despite an error in a subroutine.  In these cases, you would
  813. use `condition-case' to establish "error handlers" to recover control
  814. in case of error.
  815.    Resist the temptation to use error handling to transfer control from
  816. one part of the program to another; use `catch' and `throw' instead.
  817. *Note Catch and Throw::.
  818. * Menu:
  819. * Signaling Errors::      How to report an error.
  820. * Processing of Errors::  What Emacs does when you report an error.
  821. * Handling Errors::       How you can trap errors and continue execution.
  822. * Error Symbols::         How errors are classified for trapping them.
  823. File: elisp,  Node: Signaling Errors,  Next: Processing of Errors,  Up: Errors
  824. How to Signal an Error
  825. ......................
  826.    Most errors are signaled "automatically" within Lisp primitives
  827. which you call for other purposes, such as if you try to take the CAR
  828. of an integer or move forward a character at the end of the buffer; you
  829. can also signal errors explicitly with the functions `error' and
  830. `signal'.
  831.    Quitting, which happens when the user types `C-g', is not considered
  832. an error, but it is handled almost like an error.  *Note Quitting::.
  833.  - Function: error FORMAT-STRING &rest ARGS
  834.      This function signals an error with an error message constructed by
  835.      applying `format' (*note String Conversion::.) to FORMAT-STRING
  836.      and ARGS.
  837.      These examples show typical uses of `error':
  838.           (error "You have committed an error.
  839.                   Try something else.")
  840.                error--> You have committed an error.
  841.                   Try something else.
  842.           
  843.           (error "You have committed %d errors." 10)
  844.                error--> You have committed 10 errors.
  845.      `error' works by calling `signal' with two arguments: the error
  846.      symbol `error', and a list containing the string returned by
  847.      `format'.
  848.      If you want to use your own string as an error message verbatim,
  849.      don't just write `(error STRING)'.  If STRING contains `%', it
  850.      will be interpreted as a format specifier, with undesirable
  851.      results.  Instead, use `(error "%s" STRING)'.
  852.  - Function: signal ERROR-SYMBOL DATA
  853.      This function signals an error named by ERROR-SYMBOL.  The
  854.      argument DATA is a list of additional Lisp objects relevant to the
  855.      circumstances of the error.
  856.      The argument ERROR-SYMBOL must be an "error symbol"--a symbol
  857.      bearing a property `error-conditions' whose value is a list of
  858.      condition names.  This is how Emacs Lisp classifies different
  859.      sorts of errors.
  860.      The number and significance of the objects in DATA depends on
  861.      ERROR-SYMBOL.  For example, with a `wrong-type-arg' error, there
  862.      are two objects in the list: a predicate that describes the type
  863.      that was expected, and the object that failed to fit that type.
  864.      *Note Error Symbols::, for a description of error symbols.
  865.      Both ERROR-SYMBOL and DATA are available to any error handlers
  866.      that handle the error: `condition-case' binds a local variable to
  867.      a list of the form `(ERROR-SYMBOL .  DATA)' (*note Handling
  868.      Errors::.).  If the error is not handled, these two values are
  869.      used in printing the error message.
  870.      The function `signal' never returns (though in older Emacs versions
  871.      it could sometimes return).
  872.           (signal 'wrong-number-of-arguments '(x y))
  873.                error--> Wrong number of arguments: x, y
  874.           (signal 'no-such-error '("My unknown error condition."))
  875.                error--> peculiar error: "My unknown error condition."
  876.      Common Lisp note: Emacs Lisp has nothing like the Common Lisp
  877.      concept of continuable errors.
  878. File: elisp,  Node: Processing of Errors,  Next: Handling Errors,  Prev: Signaling Errors,  Up: Errors
  879. How Emacs Processes Errors
  880. ..........................
  881.    When an error is signaled, `signal' searches for an active "handler"
  882. for the error.  A handler is a sequence of Lisp expressions designated
  883. to be executed if an error happens in part of the Lisp program.  If the
  884. error has an applicable handler, the handler is executed, and control
  885. resumes following the handler.  The handler executes in the environment
  886. of the `condition-case' that established it; all functions called
  887. within that `condition-case' have already been exited, and the handler
  888. cannot return to them.
  889.    If there is no applicable handler for the error, the current command
  890. is terminated and control returns to the editor command loop, because
  891. the command loop has an implicit handler for all kinds of errors.  The
  892. command loop's handler uses the error symbol and associated data to
  893. print an error message.
  894.    An error that has no explicit handler may call the Lisp debugger.
  895. The debugger is enabled if the variable `debug-on-error' (*note Error
  896. Debugging::.) is non-`nil'.  Unlike error handlers, the debugger runs
  897. in the environment of the error, so that you can examine values of
  898. variables precisely as they were at the time of the error.
  899.